package com.client.until;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author chengyadong
 * @date 2023/11/28 16:44
 * @description 远程调用实现类
 */
@Component
public class RestTemplateUtils {
	public static <T> JSONObject httpPostRequestForEntity(String url, T entity, String token) {
		try {
			RestTemplate restTemplate = new RestTemplate();
			HttpHeaders headers = new HttpHeaders();
			headers.set("Authorization", "Bearer " + token);
			HttpEntity<T> httpEntity = new HttpEntity<T>(entity, headers);
			List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
			httpMessageConverters.forEach(httpMessageConverter -> {
				if (httpMessageConverter instanceof StringHttpMessageConverter) {
					StringHttpMessageConverter messageConverter = (StringHttpMessageConverter) httpMessageConverter;
					messageConverter.setDefaultCharset(StandardCharsets.UTF_8);
				}
			});
			ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
			if (response.getStatusCodeValue() == 200)
				return JSONObject.parseObject(response.getBody());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
